package com.ddd.test.exception;

import org.springframework.context.NoSuchMessageException;
import org.springframework.context.support.MessageSourceAccessor;

import com.ddd.test.i18n.CommonMessageSource;

/**
 * 通知异常类
 *
 * 
 */
public class BusinessException extends Exception {

  private static final long serialVersionUID = -4275982902797098679L;

  private final int code;

  private final String message;

  private final MessageSourceAccessor accessor;


  public BusinessException(int code) {
    this(null, null, code, null);
  }

  public BusinessException(int code, Object[] args) {
    this(null, null, code, args);
  }

  public BusinessException(String message, int code) {
    this(message, null, code, null);
  }

  public BusinessException(String message, Throwable cause, int code) {
    this(message, cause, code, null);
  }

  public BusinessException(Throwable cause, int code) {
    this(null, cause, code, null);
  }

  public BusinessException(String message, Throwable cause, int code, Object[] args) {
    super(message, cause);
    this.accessor = CommonMessageSource.getAccessor();
    this.code = code;
    this.message = resolveMessage(message, code, args);
  }

  /**
   * 异常错误码
   */
  public int getCode() {
    return code;
  }

  /**
   * 异常的错误信息<br> 如果自定义异常信息不为空,则返回自定义异常信息,否则返回默认异常信息
   */
  public String getMessage() {
    return null != message ? message : super.getMessage();
  }

  private String resolveMessage(String message, int code, Object[] args) {
    if (null != message) {
      return message;
    }
    String resolvedMessage = null;
    try {
      if (null == args) {
        resolvedMessage = accessor.getMessage(String.valueOf(code));
      } else {
        resolvedMessage = accessor.getMessage(String.valueOf(code), args);
      }
    } catch (NoSuchMessageException ex) {
    }
    return resolvedMessage;
  }

}
